const api = require('../../../../ws_micro_shop/utils/api.js');
const tools = require('../../../../ws_micro_shop/utils/getuserinfo.js');
const app = getApp();

Page({
  data: {
    address: null,
    offline: 1,
    offlineClick: false,
    chooseAddr: false,
    chooseShop: false,
    open_setting: false,
    unit: '',
    payment: -1,
    paytype: -1,
    btnFreezen: false,
    focusTel: false,
    imgUrl: app.imgUrl,
  },
  onLoad(opts) {
    let that = this;
    let options = opts || {};
    let isMulti = app.ws_micro_shop_globalData && app.ws_micro_shop_globalData.isMulti;  // 是否为多店
    let isSingle = app.ws_micro_shop_globalData && app.ws_micro_shop_globalData.isSingle; // 是否为单店
    app.tabbarindex = options.tabbarindex ? options.tabbarindex - 0 : app.tabbarindex;
    let userinfo = wx.getStorageSync('user_info');
    Number(userinfo.info) === 0 && tools.onGetInfo(this, userinfo.auth_mode);
    app.loadShopSetting().then(res => {
      that.setData({
        checkmobile: res.check_mobile,
      });
    });
    app.loadCurrencyUnit().then(res => {
      that.setData({
        unit: res.unit,
        currency: res.currency,
      });
    });
    app.pageOnLoad(this);
    let goods_info = options.goods_info;
    let goods = JSON.parse(goods_info);
    this.setData({
      options,
      type: goods.type,
      parent_id: goods.parent_id || 0,
      opts: options,
      isMulti,
      isSingle,
      version_type: app.ws_micro_shop_globalData.version_type,
    });
  },
  onShow() {
    let address = wx.getStorageSync('picker_address');
    if (address) {
      this.setData({
        address,
        name: address.name,
        mobile: address.mobile,
      });
      wx.removeStorageSync('picker_address');
    }
    this.getOrderData(this.data.options);
  },
  getOrderData(options) {
    let that = this;
    let address_id = '';
    let shop_id = '';
    let pay_type = -1;
    if (that.data.address && that.data.address.id) {
      address_id = that.data.address.id;
    }
    if (that.data.shop && that.data.shop.id) {
      shop_id = that.data.shop.id;
    }
    pay_type = that.data.paytype;
    if (options.goods_info) {
      wx.showLoading({
        title: '正在加载',
        mask: true,
      });
      app.ws_micro_shoprequest({
        url: api.group.submit_preview,
        data: {
          goods_info: options.goods_info,
          address_id: address_id,
          shop_id: shop_id,
          type: that.data.type,
          pay_type: pay_type,
        },
        success: function(res) {
          wx.hideLoading();
          if (res.code === 0 || res.code === 3) {
            let shop_list = res.data.shop_list;
            let shop = false;
            if (res.data.is_shop) {
              shop = res.data.is_shop;
            }
            that.calcPrice(res.data.total_price, res.data.colonel, res.data.express_price, res.data.gst_rate || 0, res.data.pst_rate || 0);
            let dataObj = {
              total_price: res.data.total_price,
              goods_list: res.data.list,
              goods_info: res.data.goods_info,
              userinfo: res.data.userinfo,
              address: res.data.address,
              coupon_list: res.data.coupon_list || '',
              send_type: res.data.send_type,
              dispatch_type: res.data.dispatch_type,
              level: res.data.level || '',
              colonel: res.data.colonel,
              shop_list_length: shop_list.length,
              shop: shop,
              is_shop: res.data.is_shop,
              card: res.data.card,
              card_discount: res.data.card_discount,
              pay_type_list: res.data.pay_type_list,
              // payment: res.data.pay_type_list[0].payment,
              postage_rules: res.data.postage_rules || '',
              gst_rate: res.data.gst_rate || 0,
              pst_rate: res.data.pst_rate || 0,
            };
            if (!that.data.chooseAddr && !that.data.chooseShop) {
              that.setData(Object.assign(dataObj, {
                res: res.data,
                name: res.data.address ? res.data.address.name : '',
                mobile: res.data.address ? res.data.address.mobile : '',
                express_price: res.data.express_price,
              }));
            } else if (that.data.chooseAddr) {
              that.setData(Object.assign({}, {
                res: res.data,
                express_price: res.data.express_price,
              }));
            } else if (that.data.chooseShop) {
              that.setData(Object.assign(dataObj, {
                express_price: res.data.express_price,
              }));
            }
            if (!that.data.offlineClick) {
              if (Number(res.data.dispatch_type) !== 0) {
                if (Number(res.data.goods_info.deliver_type) === 2) {
                  that.setData({
                    offline: 2,
                  });
                } else {
                that.setData({
                  offline: 3,
                });
                }
              } else {
                if (Number(res.data.goods_info.deliver_type) === 2) {
                  that.setData({
                    offline: 2,
                  });
                } else {
                  that.setData({
                    offline: 1,
                  });
                }
              }
            }

            // 处理支付方式展示数据
            let { pay_type_list, offline } = that.data;
            that.setData({
              new_pay_type_list: that.getPayTypeList(pay_type_list, offline),
            })
          }
          if (res.code === 1) {
            wx.showModal({
              title: '提示',
              content: res.msg,
              showCancel: false,
              confirmText: '确定',
              success: function (resp) {
                if (resp.confirm) {
                  wx.navigateBack({
                    delta: 1,
                  });
                }
              },
            });
          } else if (res.code === 3 && Number(that.data.offline) === 3) {
            wx.showModal({
              title: '提示',
              content: res.msg,
              showCancel: false,
              confirmText: '确定',
            });
          } else if (res.code === 2) {
            wx.showModal({
              title: '友情提示',
              content: '当前收货地址缺失经纬度，请重新编辑',
              showCancel: false,
              success: function (resp) {
                if (resp.confirm) {
                  app.util.navigateTo('ws_micro_shop/pages/address-edit/address-edit', { id: res.data.address_id, address_switch: res.data.address_switch }, false);
                }
              },
            });
          }
        },
      });
    }
  },
  calcPrice(total, colonel, express, gst_rate, pst_rate) {
    let total_price_1;
    let card_discount = this.data.card_discount;
    if (Number(this.data.offline) === 2) {
      total_price_1 = parseFloat((total - colonel) > 0 ? (total - colonel) : 0.01);
      if (Number(this.data.payment) === 5 && card_discount) {
        total_price_1 = total_price_1 * card_discount / 10;
      }
    } else {
      total_price_1 = parseFloat((total - colonel) > 0 ? (total - colonel) : 0.01);
      if (Number(this.data.payment) === 5 && card_discount) {
        total_price_1 = total_price_1 * card_discount / 10 + express;
      } else {
        total_price_1 = total_price_1 + express;
      }
    }
    if (gst_rate > 0 || pst_rate > 0) {
      total_price_1 = total_price_1 + gst_rate + pst_rate;
    }
    this.setData({
      total_price_1: total_price_1.toFixed(2),
    });
  },
  bindkeyinput(e) {
    this.setData({
      content: e.detail.value,
    });
  },
  orderSubmit(e) {
    let that = this;
    let data = {};
    let offline = Number(that.data.offline);
    let dispatch_type = Number(that.data.dispatch_type);
    let { isMulti, isSingle, btnFreezen, version_type } = that.data;

    // if (btnFreezen) {
    //   return false;
	  // }
    that.setData({
      btnFreezen: true,
    })
    data.offline = offline;
    app.getSubscribeMessage(3).then(res => {
    if (offline === 1) {
      if (!that.data.address || !that.data.address.id) {
        that.setData({
          btnFreezen: false,
        })
        wx.showToast({
          title: '请选择收货地址',
          icon: 'none',
        });
        return;
      }
      data.address_id = that.data.address.id;
    } else if (offline === 3) {
      if (!that.data.address || !that.data.address.id) {
        that.setData({
          btnFreezen: false,
        })
        wx.showToast({
          title: '请选择收货地址',
          icon: 'none',
        });
        return;
      }
      data.address_id = that.data.address.id;
      if (!that.data.shop || !that.data.shop.id) {
        that.setData({
          btnFreezen: false,
        })
        wx.showToast({
          title: '请选择同城配送的门店',
          icon: 'none',
        });
        return;
      }
      data.shop_id = that.data.shop.id;
    } else {
      if (that.data.res.require_verify != 2) {
        data.address_name = that.data.name;
        data.address_mobile = that.data.mobile;
      }

      if (isSingle && !that.data.shop_list_length) {
        wx.showToast({
          title: '您购买的商品没有合适的自提站点',
          icon: 'none',
        });
        that.setData({
          btnFreezen: false,
        })
        return;
      }

      if (that.data.shop && that.data.shop.id) {
        data.shop_id = that.data.shop.id;
      } else {
        that.setData({
          btnFreezen: false,
        })
        wx.showToast({
          title: '请选择自提站点',
          icon: 'none',
        });
        return;
      }

      if (offline === 2 && Number(that.data.res.require_verify) === 1) {
        if (!data.address_name) {
          that.setData({
            btnFreezen: false,
          })
        wx.showToast({
            title: '请填写收货人',
          icon: 'none',
        });
        return;
      }

        if (!data.address_mobile) {
          that.setData({
            btnFreezen: false,
          })
          wx.showToast({
            title: '请填写联系方式',
            icon: 'none',
          });
          return;
        } else {
        if (Number(that.data.checkmobile) === 1) {
          if (that.data.currency === 'CNY') {
            let check_mobile = app.util.phoneExp.mobile;
            let check_phone = app.util.phoneExp.landline;
            if (!check_mobile.test(data.address_mobile) && !check_phone.test(data.address_mobile)) {
              that.setData({
                btnFreezen: false,
              })
              wx.showToast({
                title: '联系电话格式不正确',
                icon: 'none',
              });
              return;
            }
          } else {
            let check_canada = app.util.phoneExp.canadaPhone;
            if (!check_canada.test(data.address_mobile)) {
              that.setData({
                btnFreezen: false,
              })
              wx.showToast({
                title: '联系电话格式不正确',
                icon: 'none',
              });
              return;
            }
          }
        }
        }
      }

      }

    if (that.data.payment === -1) {
      that.setData({
        btnFreezen: false,
      })
      return wx.showToast({
        title: '请选择支付方式',
        icon: 'none',
      });
    }

    that.data.goods_info && (data.goods_info = JSON.stringify(that.data.goods_info));
    that.data.picker_coupon && (data.user_coupon_id = that.data.picker_coupon.user_coupon_id);
    that.data.content && (data.content = that.data.content);
    that.data.type && (data.type = that.data.type);
    that.data.parent_id && (data.parent_id = that.data.parent_id);
    data.payment = that.data.payment;
    let last_share_guide_id = app.ws_micro_shop_globalData.last_share_guide_id;
    let last_share_good_id = Number(app.ws_micro_shop_globalData.last_share_good_id);
    if (version_type === '1' || version_type === '3') {
      let hasGoods = (last_share_good_id === Number(JSON.parse(data.goods_info).goods_id))
      if (last_share_guide_id && hasGoods) {
        data.staff_id = last_share_guide_id;
        data.staff_gid = last_share_good_id;
      } 
    }

    wx.showLoading({
      title: '正在提交',
      mask: true,
    });

    app.ws_micro_shoprequest({
      url: api.group.submit,
      method: 'POST',
      data,
      success: function(res) {
        if (res.code === 0) {
          setTimeout(function() {
            wx.hideLoading();
          }, 1000);
          setTimeout(function() {
            that.setData({
              options: {},
            });
          }, 1);
          let order_id = res.data.order_id;
          if (Number(data.payment) === 0) {
            setTimeout(function() {
              wx.hideLoading();
            }, 1000);
            app.ws_micro_shoprequest({
              url: api.group.pay_data,
              data: {
                order_id,
                pay_type: 'WECHAT_PAY',
              },
              success: function(res) {
                if (res.code === 0) {
                  wx.requestPayment({
                    timeStamp: res.data.timeStamp,
                    nonceStr: res.data.nonceStr,
                    package: res.data.package,
                    signType: res.data.signType,
                    paySign: res.data.paySign,
                    success: function(e) {
                      if (that.data.type === 'ONLY_BUY') {
                        app.util.navigateTo('/ws_micro_shop/pages/order/order', {
                          status: 1,
                        }, true);
                      } else {
                        wx.redirectTo({
                          url: '/ws_micro_shop_pt/pages/pt/group/details?oid=' + order_id,
                        });
                      }
                    },
                    complete: function(e) {
                      if (e.errMsg === 'requestPayment:fail' || e.errMsg === 'requestPayment:fail cancel') {
                        wx.showModal({
                          title: '提示',
                          content: '订单尚未支付',
                          showCancel: false,
                          confirmText: '确认',
                          success: function(res) {
                            if (res.confirm) {
                              app.util.navigateTo('/ws_micro_shop/pages/order/order', {
                                status: 0,
                              }, true);
                            }
                          },
                        });
                        return;
                      }
                      if (e.errMsg === 'requestPayment:ok') {
                        that.setData({
                          btnFreezen: false,
                        });
                        return;
                      }
                      app.util.navigateTo('/ws_micro_shop/pages/order/order', {
                        status: -1,
                      }, true);
                    },
                  });
                  return;
                }
                if (res.code === 1) {
                  wx.showToast({
                    title: res.msg,
                    icon: 'none',
                  });
                  setTimeout(function () {
                    app.util.navigateTo(
                      '/ws_micro_shop/pages/order/order',
                      { status: 0 },
                      true
                    );
                  }, 1000);
                  return;
                }
              },
            });
          }
          if (Number(data.payment) === 2) {
            app.ws_micro_shoprequest({
              url: api.group.pay_data,
              data: {
                order_id: order_id,
                pay_type: 'HUODAO_PAY',
                form_id: e.detail.formId,
              },
              success: function(res) {
                wx.hideLoading();
                if (res.code === 0) {
                  app.util.navigateTo('/ws_micro_shop/pages/order/order', {
                    status: 1,
                  }, true);
                } else {
                  wx.showToast({
                    title: res.msg,
                    icon: 'none',
                  });
                  setTimeout(function () {
                    app.util.navigateTo(
                      '/ws_micro_shop/pages/order/order',
                      { status: 0 },
                      true
                    );
                  }, 1000);
                  return;
                }
              },

            });
          }
          if (Number(data.payment) === 3) {
            app.ws_micro_shoprequest({
              url: api.group.pay_data,
              data: {
                order_id: order_id,
                pay_type: 'BALANCE_PAY',
                form_id: e.detail.formId,
              },
              success: function(res) {
                wx.hideLoading();
                if (res.code === 0) {
                  if (that.data.type === 'ONLY_BUY') {
                    app.util.navigateTo('/ws_micro_shop/pages/order/order', {
                      status: 1,
                    }, true);
                  } else {
                    wx.redirectTo({
                      url: '/ws_micro_shop_pt/pages/pt/group/details?oid=' + order_id,
                    });
                  }
                } else {
                  wx.showToast({
                    title: res.msg,
                    icon: 'none',
                  });
                  setTimeout(function() {
                    app.util.navigateTo('/ws_micro_shop/pages/order/order', {
                      status: 0,
                    }, true);
                  }, 1000);
                  return;
                }
              },
            });
          }
          if (Number(data.payment) === 5) {
            app.ws_micro_shoprequest({
              url: api.group.pay_data,
              data: {
                order_id: order_id,
                pay_type: 'CARD_PAY',
                form_id: e.detail.formId,
              },
              success: function (res) {
                wx.hideLoading();
                if (res.code === 0) {
                  if (that.data.type === 'ONLY_BUY') {
                    app.util.navigateTo('/ws_micro_shop/pages/order/order', {
                      status: 1,
                    }, true);
                  } else {
                    wx.redirectTo({
                      url: '/ws_micro_shop_pt/pages/pt/group/details?oid=' + order_id,
                    });
                  }
                } else {
                  wx.showToast({
                    title: res.msg,
                    icon: 'none',
                  });
                  setTimeout(function () {
                    app.util.navigateTo('/ws_micro_shop/pages/order/order', {
                      status: 0,
                    }, true);
                  }, 1000);
                  return;
                }
              },
            });
          }
          if (Number(data.payment) === 6) {
            app.ws_micro_shoprequest({
              url: api.group.pay_data,
              data: {
                order_id: order_id,
                pay_type: 'CLERK_PAY',
                form_id: e.detail.formId,
              },
              success: function (res) {
                wx.hideLoading();
                if (res.code === 0) {
                  app.util.navigateTo('/ws_micro_shop/pages/order/order', {
                    status: 1,
                  }, true);
                } else {
                  wx.showToast({
                    title: res.msg,
                    icon: 'none',
                  });
                  setTimeout(function () {
                    app.util.navigateTo(
                      '/ws_micro_shop/pages/order/order',
                      { status: 0 },
                      true
                    );
                  }, 1000);
                  return;
                }
              },

            });
          }
        }
        if (res.code === 1) {
          wx.hideLoading();
          that.setData({
            btnFreezen: false,
          })
          wx.showModal({
            title: '提示',
            content: res.msg,
            showCancel: false,
            confirmText: '确定',
            success: function (resp) {
              if (resp.confirm) {
                wx.navigateBack({
                  delta: 1,
                });
              }
            },
          });
        }
      },
    });
    })
  },
  KeyName(e) {
    this.setData({
      name: e.detail.value,
    });
  },
  nameComfirm() {
    this.setData({
      focusTel: true,
    });
  },
  KeyMobile(e) {
    this.setData({
      mobile: e.detail.value,
    });
  },
  getOffline(e) {
    let offline = Number(e.target.dataset.index);
    let { pay_type_list, card_discount, payment, res: { total_price, colonel, express_price } = {} } = this.data;
    let total_price_1 = parseFloat((total_price - colonel) > 0 ? (total_price - colonel) : 0.01);
    // offline !== this.data.offline && this.setData({ payment: -1 });  // 清空支付方式
    if (offline === 1) {
      if (payment === 5 && card_discount) {
        total_price_1 = total_price_1 * card_discount / 10 + express_price;
      } else {
        total_price_1 = total_price_1 + express_price;
      }
      this.setData({
        offline: 1,
        express_price: express_price,
        total_price_1: total_price_1.toFixed(2),
      });
    } else if (offline === 2) {
      let total_price = (total_price_1).toFixed(2);
      if (payment === 5 && card_discount) {
        total_price = total_price * card_discount / 10;
      }
      this.setData({
        offline: 2,
        express_price: 0,
        total_price_1: total_price,
      });
    } else {
      if (payment === 5 && card_discount) {
        total_price_1 = total_price_1 * card_discount / 10 + express_price;
      } else {
        total_price_1 = total_price_1 + express_price;
      }
      this.setData({
        offline: 3,
        express_price: express_price,
        total_price_1: total_price_1.toFixed(2),
      });
    }

    // 切换物流方式时处理支付方式
    let new_pay_type_list = this.getPayTypeList(pay_type_list, offline);
    ((offline !== 2 && payment === 6) || (offline === 2 && payment === 2)) && (payment = -1);  // 清空支付方式
    this.setData({
      offlineClick: true,
      new_pay_type_list,
      payment,
      indexNum: payment === -1 ? 0 : app.getpayment(new_pay_type_list, payment),
    });
  },
  showShop() {
    this.dingwei('');
    if (this.data.shop_list_length >= 1) {
      this.setData({
        show_shop: true,
        chooseShop: true,
      });
    }
  },
  showNearestShop() {
    this.dingwei('');
    if (this.data.shop_list_length >= 1) {
      this.setData({
        show_shop: true,
        chooseShop: true,
      });
    }
  },
  toPickAddr(e) {
    let param = e.currentTarget.dataset;
    this.setData({
      chooseAddr: true,
    });
    app.ws_micro_shop_navigate(param);
  },

  dingwei(e) {
    let that = this;
    let hit = e && e.currentTarget.dataset.flag;
    wx.getSetting({
      success(res) {
        if (typeof res.authSetting['scope.userLocation'] === 'undefined') {
          wx.getLocation({
            type: 'wgs84',
            altitude: false,
            success: res => {
              that.getShopLists(res.longitude, res.latitude);
            }
          });
        } else if (res.authSetting['scope.userLocation'] === false) {
          that.setData({
            open_setting: true,
          });
        } else {
          
          if (hit) { //点击了手动定位
          wx.chooseLocation({
            success: function (res) {
              that.setData({
                location: res.address,
              });
              that.getShopLists(res.longitude, res.latitude);
            },
          });
          } else {
            wx.getLocation({
              type: 'wgs84',
              altitude: false,
              success: res => {
                that.getShopLists(res.longitude, res.latitude);
              }
            });
          }

        }
      },
    });
  },
  getShopLists(longitude, latitude) {
    let that = this;
    app.ws_micro_shoprequest({
      url: api.order.shop_list,
      data: {
        longitude,
        latitude,
        goods_id_str: that.data.goods_info && that.data.goods_info.goods_id + '',
        goods_type: 'pingtuan'
      },
      success: function(res) {
        if (res.code === 0) {
          that.setData({
            shop_list: res.data,
          });
        }
      },
    });
  },
  pickShop(e) {
    let index = Number(e.currentTarget.dataset.index);
    if (index === -1) {
      this.setData({
        shop: false,
        show_shop: false,
      });
    } else {
      this.setData({
        shop: this.data.shop_list[index],
        show_shop: false,
      });
    }
    this.getOrderData(this.data.options);
  },
  showPayment() {
    this.setData({
      // show_payment: true,
    });
  },
  getPayTypeList(pay_type_list, offline) {
    let pay_list = [];
    for (let i in pay_type_list) {
      if (Object.prototype.hasOwnProperty.call(pay_type_list, i)) {
        let item = pay_type_list[i];
        if (((item.payment != 2 && offline == 2) || (item.payment == 6 && offline == 2)) || (offline == 1 && item.payment != 6) || (offline == 3 && item.payment != 6)) pay_list.push(item);
      }
    }
    return pay_list;
  },
  payPicker(e) {
    let index = e.currentTarget.dataset.index;
    this.setData({
      payment: index,
    });
  },
  payClose(e) {
    let that = this;
    let index = e.detail.value;
    let { new_pay_type_list, payment: oldpayment = -1 } = that.data;
    let paytype = Number(new_pay_type_list[index].payment);
    if (Number(oldpayment) === paytype) return;
    that.setData({
      payment: paytype,
      paytype,
      indexNum: app.getpayment(new_pay_type_list, paytype),
    })
    if (Number(paytype) === 3) {
      wx.showModal({
        title: '友情提示',
        content: '是否确定选择账户余额支付',
        success: function(res) {
          if (res.confirm) {
            // that.getOrderData(that.data.options);
            that.setData({
              show_payment: false,
            });
          }
        },
      });
    } else if (Number(paytype) === 5) {
      let card = that.data.card;
      if (card) {
        // that.getOrderData(that.data.options);
        that.setData({
          show_payment: false,
        });
      } else {
        wx.showModal({
          title: '友情提示',
          content: '你还未开通会员卡，是否前往个人中心开通？',
          success: function (res) {
            if (res.confirm) {
              app.util.navigateTo('/ws_micro_shop/pages/user/user', {}, false);
            }
          },
        });
      }
    } else {
      // that.getOrderData(that.data.options);
      that.setData({
        show_payment: false,
      });
    }
    this.calcPrice(this.data.total_price, this.data.colonel, this.data.express_price, this.data.gst_rate, this.data.pst_rate);
  },
});
